﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using DiscoveryLogic.Analytics.BusinessLogic.Entities;
using DiscoveryLogic.Analytics.DataObjects;
using DiscoveryLogic.Analytics.UI.Common.Events;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Wpf.Events;

namespace DiscoveryLogic.Analytics.Modules.Entities
{
    public class GrantListPresenter
    {
        private GrantListView _View;
		/// <summary></summary>
		public GrantListView View
		{
			get
			{
				return this._View;
			}
            set
            {
                this._View = value;
                this._View.GrantSelected += new GrantListView.OnGrantSelected(SelectGrant);
                this._View.Grants = this.ReadGrantList();
            }
		}

		private readonly IEventAggregator _EventAggregator;
        private SubscriptionToken _SubscriptionToken;

        public GrantListPresenter(IEventAggregator eventAggregator)
		{
			this._EventAggregator = eventAggregator;
		}

        public void SelectGrant(GrantDO grant)
        {
            if (grant != null)
            {
                this._EventAggregator.GetEvent<GrantSelectedEvent>().Publish(grant);
            }
        }

        public void RegisterGrantSelectionChangedEventHandler(GrantDO grant)
        {
            GrantSelectedEvent grantSelectedEvent =
                    _EventAggregator.GetEvent<GrantSelectedEvent>();
            if (this._SubscriptionToken != null)
            {
                grantSelectedEvent.Unsubscribe(_SubscriptionToken);
            }
            this._SubscriptionToken = grantSelectedEvent.Subscribe(
                GrantSelectedHandler,
                ThreadOption.UIThread,
                false);
        }

        private void GrantSelectedHandler(GrantDO grant)
        {
            this._View.SelectGrant(grant);
        }

        private List<GrantDO> ReadGrantList()
        {
            return EntityManager.GeneratGrantsForTest();
        }
    }
}
